package com.future.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.future.allUtils.utils.CacheClient;
import com.future.allUtils.utils.SecurityUtils;
import com.future.domain.*;
import com.future.domain.DTO.*;
import com.future.domain.vo.MediaResourceVO;
import com.future.mapper.*;
import com.future.service.SearchService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserClassMapper userClassMapper;
    @Autowired
    private StudentClassMapper studentClassMapper;
    @Autowired
    private MediaResourceMapper mediaResourceMapper;
    @Autowired
    private CertificationMapper certificationMapper;
    @Autowired
    private CacheClient cacheClient;

    // 0搜索所有，1搜索用户，2搜索文章，3搜索视频
    @Override
    public SearchResultDTO receptionSearch(SearchDTO searchDTO) {
        // 分页参数校验
        if (searchDTO.getPageNum() == null || searchDTO.getPageNum() <= 0) {
            searchDTO.setPageNum(1);
        }
        if (searchDTO.getPageSize() == null || searchDTO.getPageSize() <= 0) {
            searchDTO.setPageSize(10);
        }
        if (searchDTO.getType() < 0 || searchDTO.getType() > 3) {
            searchDTO.setType(0);
        }
        SearchResultDTO resultDTO = new SearchResultDTO();

        // ===== 类型0：搜索全部（文章+用户+视频）=====
        if (searchDTO.getType() == 0) {
            String cacheKey = "search:reception:type:0:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询全部数据
                        SearchResultDTO dto = new SearchResultDTO();
                        // 1. 搜索文章
                        Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<Article> articles = articleMapper.receptionSearchArticles(articlePage, searchDTO.getKeyword());
                        List<Article> articleList = articles.getRecords().stream()
                                .map(article -> {
                                    article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                                    return article;
                                }).collect(Collectors.toList());
                        dto.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));

                        // 2. 搜索用户
                        Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<User> users = userMapper.receptionSearchUsers(userPage, searchDTO.getKeyword());
                        List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                                .map(user -> {
                                    UserBackEndDTO userDTO = new UserBackEndDTO();
                                    BeanUtils.copyProperties(user, userDTO);
                                    userDTO.setAuthorIdStr(user.getId().toString());
                                    return userDTO;
                                }).collect(Collectors.toList());
                        dto.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));
                        // 3. 搜索视频
                        Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<MediaResource> medias = mediaResourceMapper.receptionSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
                        List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                                .map(media -> {
                                    MediaResourceVO vo = new MediaResourceVO();
                                    BeanUtils.copyProperties(media, vo);
                                    User upLoader = userMapper.selectById(media.getUploaderId());
                                    if (upLoader != null) {
                                        vo.setAvatar(upLoader.getAvatar());
                                        vo.setUsername(upLoader.getUsername());
                                    }
                                    return vo;
                                }).collect(Collectors.toList());
                        dto.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询（复用重建逻辑中的代码）
            // 1. 搜索文章
            Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<Article> articles = articleMapper.receptionSearchArticles(articlePage, searchDTO.getKeyword());
            List<Article> articleList = articles.getRecords().stream()
                    .map(article -> {
                        article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                        return article;
                    }).collect(Collectors.toList());
            resultDTO.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));

            // 2. 搜索用户
            Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<User> users = userMapper.receptionSearchUsers(userPage, searchDTO.getKeyword());
            List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                    .map(user -> {
                        UserBackEndDTO dto = new UserBackEndDTO();
                        BeanUtils.copyProperties(user, dto);
                        dto.setAuthorIdStr(user.getId().toString());
                        return dto;
                    }).collect(Collectors.toList());
            resultDTO.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));

            // 3. 搜索视频
            Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<MediaResource> medias = mediaResourceMapper.receptionSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
            List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                    .map(media -> {
                        MediaResourceVO vo = new MediaResourceVO();
                        BeanUtils.copyProperties(media, vo);
                        User upLoader = userMapper.selectById(media.getUploaderId());
                        if (upLoader != null) {
                            vo.setAvatar(upLoader.getAvatar());
                            vo.setUsername(upLoader.getUsername());
                        }
                        return vo;
                    }).collect(Collectors.toList());
            resultDTO.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型2：搜索文章 =====
        if (searchDTO.getType() == 2) {
            String cacheKey = "search:reception:type:2:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询文章数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<Article> articles = articleMapper.receptionSearchArticles(articlePage, searchDTO.getKeyword());
                        List<Article> articleList = articles.getRecords().stream()
                                .map(article -> {
                                    article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                                    return article;
                                }).collect(Collectors.toList());
                        dto.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<Article> articles = articleMapper.receptionSearchArticles(articlePage, searchDTO.getKeyword());
            List<Article> articleList = articles.getRecords().stream()
                    .map(article -> {
                        article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                        return article;
                    }).collect(Collectors.toList());
            resultDTO.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型1：搜索用户 =====
        if (searchDTO.getType() == 1) {
            String cacheKey = "search:reception:type:1:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询用户数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<User> users = userMapper.receptionSearchUsers(userPage, searchDTO.getKeyword());
                        List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                                .map(user -> {
                                    UserBackEndDTO userDTO = new UserBackEndDTO();
                                    BeanUtils.copyProperties(user, userDTO);
                                    userDTO.setAuthorIdStr(user.getId().toString());
                                    return userDTO;
                                }).collect(Collectors.toList());
                        dto.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<User> users = userMapper.receptionSearchUsers(userPage, searchDTO.getKeyword());
            List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                    .map(user -> {
                        UserBackEndDTO dto = new UserBackEndDTO();
                        BeanUtils.copyProperties(user, dto);
                        dto.setAuthorIdStr(user.getId().toString());
                        return dto;
                    }).collect(Collectors.toList());
            resultDTO.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型3：搜索视频 =====
        if (searchDTO.getType() == 3) {
            String cacheKey = "search:reception:type:3:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询视频数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<MediaResource> medias = mediaResourceMapper.receptionSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
                        List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                                .map(media -> {
                                    MediaResourceVO vo = new MediaResourceVO();
                                    BeanUtils.copyProperties(media, vo);
                                    User upLoader = userMapper.selectById(media.getUploaderId());
                                    if (upLoader != null) {
                                        vo.setAvatar(upLoader.getAvatar());
                                        vo.setUsername(upLoader.getUsername());
                                    }
                                    return vo;
                                }).collect(Collectors.toList());
                        dto.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<MediaResource> medias = mediaResourceMapper.receptionSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
            List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                    .map(media -> {
                        MediaResourceVO vo = new MediaResourceVO();
                        BeanUtils.copyProperties(media, vo);
                        User upLoader = userMapper.selectById(media.getUploaderId());
                        if (upLoader != null) {
                            vo.setAvatar(upLoader.getAvatar());
                            vo.setUsername(upLoader.getUsername());
                        }
                        return vo;
                    }).collect(Collectors.toList());
            resultDTO.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        return resultDTO;
    }

    // 0搜索所有，1搜索用户，2搜索文章，3搜索视频，4搜索审核
    @Override
    public SearchResultDTO backgroundSearch(SearchDTO searchDTO) {
        // 分页参数校验
        if (searchDTO.getPageNum() == null || searchDTO.getPageNum() <= 0) {
            searchDTO.setPageNum(1);
        }
        if (searchDTO.getPageSize() == null || searchDTO.getPageSize() <= 0) {
            searchDTO.setPageSize(10);
        }
        if (searchDTO.getType() < 0 || searchDTO.getType() > 4) {
            searchDTO.setType(0);
        }
        SearchResultDTO resultDTO = new SearchResultDTO();

        // ===== 类型0：搜索全部（文章+用户+视频+认证）=====
        if (searchDTO.getType() == 0) {
            String cacheKey = "search:background:type:0:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询全部数据
                        SearchResultDTO dto = new SearchResultDTO();
                        // 1. 搜索文章
                        Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<Article> articles = articleMapper.backgroundSearchArticles(articlePage, searchDTO.getKeyword());
                        List<Article> articleList = articles.getRecords().stream()
                                .map(article -> {
                                    article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                                    return article;
                                }).collect(Collectors.toList());
                        dto.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));

                        // 2. 搜索用户
                        Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<User> users = userMapper.backgroundSearchUsers(userPage, searchDTO.getKeyword());
                        List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                                .map(user -> {
                                    UserBackEndDTO userDTO = new UserBackEndDTO();
                                    BeanUtils.copyProperties(user, userDTO);
                                    userDTO.setAuthorIdStr(user.getId().toString());
                                    return userDTO;
                                }).collect(Collectors.toList());
                        dto.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));

                        // 3. 搜索视频
                        Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<MediaResource> medias = mediaResourceMapper.backgroundSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
                        List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                                .map(media -> {
                                    MediaResourceVO vo = new MediaResourceVO();
                                    BeanUtils.copyProperties(media, vo);
                                    User upLoader = userMapper.selectById(media.getUploaderId());
                                    if (upLoader != null) {
                                        vo.setAvatar(upLoader.getAvatar());
                                        vo.setUsername(upLoader.getUsername());
                                    }
                                    return vo;
                                }).collect(Collectors.toList());
                        dto.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));

                        // 4. 搜索认证
                        Page<Certification> certificationPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<Certification> certifications = certificationMapper.searchCertifications(certificationPage, searchDTO.getKeyword());
                        List<Certification> certificationList = certifications.getRecords().stream()
                                .map(cert -> {
                                    User applicant = userMapper.selectById(cert.getUserId());
                                    if (applicant != null) {
                                        cert.setUsername(applicant.getUsername());
                                        cert.setAvatar(applicant.getAvatar());
                                    }
                                    return cert;
                                }).collect(Collectors.toList());
                        dto.setCertification(new PageDTO<>(certificationList, certifications.getTotal(), certifications.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            // 1. 搜索文章
            Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<Article> articles = articleMapper.backgroundSearchArticles(articlePage, searchDTO.getKeyword());
            List<Article> articleList = articles.getRecords().stream()
                    .map(article -> {
                        article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                        return article;
                    }).collect(Collectors.toList());
            resultDTO.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));

            // 2. 搜索用户
            Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<User> users = userMapper.backgroundSearchUsers(userPage, searchDTO.getKeyword());
            List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                    .map(user -> {
                        UserBackEndDTO dto = new UserBackEndDTO();
                        BeanUtils.copyProperties(user, dto);
                        dto.setAuthorIdStr(user.getId().toString());
                        return dto;
                    }).collect(Collectors.toList());
            resultDTO.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));

            // 3. 搜索视频
            Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<MediaResource> medias = mediaResourceMapper.backgroundSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
            List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                    .map(media -> {
                        MediaResourceVO vo = new MediaResourceVO();
                        BeanUtils.copyProperties(media, vo);
                        User upLoader = userMapper.selectById(media.getUploaderId());
                        if (upLoader != null) {
                            vo.setAvatar(upLoader.getAvatar());
                            vo.setUsername(upLoader.getUsername());
                        }
                        return vo;
                    }).collect(Collectors.toList());
            resultDTO.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));

            // 4. 搜索认证
            Page<Certification> certificationPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<Certification> certifications = certificationMapper.searchCertifications(certificationPage, searchDTO.getKeyword());
            List<Certification> certificationList = certifications.getRecords().stream()
                    .map(cert -> {
                        User applicant = userMapper.selectById(cert.getUserId());
                        if (applicant != null) {
                            cert.setUsername(applicant.getUsername());
                            cert.setAvatar(applicant.getAvatar());
                        }
                        return cert;
                    }).collect(Collectors.toList());
            resultDTO.setCertification(new PageDTO<>(certificationList, certifications.getTotal(), certifications.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型2：搜索文章 =====
        if (searchDTO.getType() == 2) {
            String cacheKey = "search:background:type:2:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询文章数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<Article> articles = articleMapper.backgroundSearchArticles(articlePage, searchDTO.getKeyword());
                        List<Article> articleList = articles.getRecords().stream()
                                .map(article -> {
                                    article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                                    return article;
                                }).collect(Collectors.toList());
                        dto.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<Article> articlePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<Article> articles = articleMapper.backgroundSearchArticles(articlePage, searchDTO.getKeyword());
            List<Article> articleList = articles.getRecords().stream()
                    .map(article -> {
                        article.setAuthorName(userMapper.selectById(article.getAuthorId()).getUsername());
                        return article;
                    }).collect(Collectors.toList());
            resultDTO.setArticle(new PageDTO<>(articleList, articles.getTotal(), articles.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型1：搜索用户 =====
        if (searchDTO.getType() == 1) {
            String cacheKey = "search:background:type:1:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询用户数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<User> users = userMapper.backgroundSearchUsers(userPage, searchDTO.getKeyword());
                        List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                                .map(user -> {
                                    UserBackEndDTO userDTO = new UserBackEndDTO();
                                    BeanUtils.copyProperties(user, userDTO);
                                    userDTO.setAuthorIdStr(user.getId().toString());
                                    return userDTO;
                                }).collect(Collectors.toList());
                        dto.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<User> userPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<User> users = userMapper.backgroundSearchUsers(userPage, searchDTO.getKeyword());
            List<UserBackEndDTO> userDTOList = users.getRecords().stream()
                    .map(user -> {
                        UserBackEndDTO dto = new UserBackEndDTO();
                        BeanUtils.copyProperties(user, dto);
                        dto.setAuthorIdStr(user.getId().toString());
                        return dto;
                    }).collect(Collectors.toList());
            resultDTO.setUserDTOs(new PageDTO<>(userDTOList, users.getTotal(), users.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型3：搜索视频 =====
        if (searchDTO.getType() == 3) {
            String cacheKey = "search:background:type:3:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询视频数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<MediaResource> medias = mediaResourceMapper.backgroundSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
                        List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                                .map(media -> {
                                    MediaResourceVO vo = new MediaResourceVO();
                                    BeanUtils.copyProperties(media, vo);
                                    User upLoader = userMapper.selectById(media.getUploaderId());
                                    if (upLoader != null) {
                                        vo.setAvatar(upLoader.getAvatar());
                                        vo.setUsername(upLoader.getUsername());
                                    }
                                    return vo;
                                }).collect(Collectors.toList());
                        dto.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<MediaResource> mediaResourcePage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<MediaResource> medias = mediaResourceMapper.backgroundSearchMediaResources(mediaResourcePage, searchDTO.getKeyword());
            List<MediaResourceVO> mediaVOlist = medias.getRecords().stream()
                    .map(media -> {
                        MediaResourceVO vo = new MediaResourceVO();
                        BeanUtils.copyProperties(media, vo);
                        User upLoader = userMapper.selectById(media.getUploaderId());
                        if (upLoader != null) {
                            vo.setAvatar(upLoader.getAvatar());
                            vo.setUsername(upLoader.getUsername());
                        }
                        return vo;
                    }).collect(Collectors.toList());
            resultDTO.setMediaResourceVo(new PageDTO<>(mediaVOlist, medias.getTotal(), medias.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        // ===== 类型4：搜索认证 =====
        if (searchDTO.getType() == 4) {
            String cacheKey = "search:background:type:4:keyword:" + searchDTO.getKeyword() + ":page:" + searchDTO.getPageNum() + ":size:" + searchDTO.getPageSize();
            // 查询缓存（带逻辑过期+自动重建）
            SearchResultDTO cachedResult = cacheClient.queryWithLogicalExpire(
                    "", cacheKey, SearchResultDTO.class,
                    id -> { // 缓存重建：查询认证数据
                        SearchResultDTO dto = new SearchResultDTO();
                        Page<Certification> certificationPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
                        Page<Certification> certifications = certificationMapper.searchCertifications(certificationPage, searchDTO.getKeyword());
                        List<Certification> certificationList = certifications.getRecords().stream()
                                .map(cert -> {
                                    User applicant = userMapper.selectById(cert.getUserId());
                                    if (applicant != null) {
                                        cert.setUsername(applicant.getUsername());
                                        cert.setAvatar(applicant.getAvatar());
                                    }
                                    return cert;
                                }).collect(Collectors.toList());
                        dto.setCertification(new PageDTO<>(certificationList, certifications.getTotal(), certifications.getPages()));
                        return dto;
                    }, 30L, TimeUnit.MINUTES
            );
            if (cachedResult != null) {
                return cachedResult;
            }

            // 缓存未命中：执行数据库查询
            Page<Certification> certificationPage = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
            Page<Certification> certifications = certificationMapper.searchCertifications(certificationPage, searchDTO.getKeyword());
            List<Certification> certificationList = certifications.getRecords().stream()
                    .map(cert -> {
                        User applicant = userMapper.selectById(cert.getUserId());
                        if (applicant != null) {
                            cert.setUsername(applicant.getUsername());
                            cert.setAvatar(applicant.getAvatar());
                        }
                        return cert;
                    }).collect(Collectors.toList());
            resultDTO.setCertification(new PageDTO<>(certificationList, certifications.getTotal(), certifications.getPages()));

            // 写入缓存
            cacheClient.setWithLogicalExpire(cacheKey, resultDTO, 30L, TimeUnit.MINUTES);
        }

        return resultDTO;
    }

    @Override
    public SearchResultDTO teacherSearch(SearchDTO searchDTO) {
        // 分页参数校验
        if (searchDTO.getPageNum() == null || searchDTO.getPageNum() <= 0) {
            searchDTO.setPageNum(1);
        }
        if (searchDTO.getPageSize() == null || searchDTO.getPageSize() <= 0) {
            searchDTO.setPageSize(10);
        }
        
        SearchResultDTO resultDTO = new SearchResultDTO();
        Page<UserBackEndDTO> page = new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize());
        
        // 查询数据库获取学生列表
        Long teacherId = SecurityUtils.getCurrentUserId();
        Page<UserBackEndDTO> students = userMapper.selectMyClassStudent(page, searchDTO.getKeyword(), teacherId);
        
        // 封装结果
        resultDTO.setUserDTOs(new PageDTO<>(students.getRecords(), students.getTotal(), students.getPages()));
        
        return resultDTO;
    }
}